package com.example.springbootdemo.web;

import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/talk/{id}")
@RestController
public class TalkAction {
    // 扩展了解: HashMap, HashTable, ConcurrentHashMap 区别
    public static Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session) throws EncodeException, IOException {
        session.getUserProperties().put("id",id);
        sessionMap.put(id, session);
        System.out.println(id + " 上线了");
        sendToAll(sessionMap.keySet());
    }

    @OnClose
    public void onClose(Session session) throws EncodeException, IOException {
        final Object id = session.getUserProperties().get("id");
        sessionMap.remove(id);
        System.out.println(id + " 下线了");
        sendToAll(sessionMap.keySet());
    }

    @OnMessage
    public void onMessage(String message, Session session) throws EncodeException, IOException {
        final Object id = session.getUserProperties().get("id");
        Msg m = new Msg(id.toString(), message);
        sendToAll(m);
    }

    // 发送给所有在线的用户
    public void sendToAll(Object msg) throws EncodeException, IOException {
        Gson gson = new Gson();
        for (Session session : sessionMap.values()) {
            final RemoteEndpoint.Basic remote = session.getBasicRemote();
            final String json = gson.toJson(msg);
            remote.sendText(json);
        }
    }

    // 私聊
    public void sendToId(String id, Object msg) throws EncodeException, IOException {
        Gson gson = new Gson();
        for (Session session : sessionMap.values()) {
            if(id.equals(session.getUserProperties().get("id"))){
                final RemoteEndpoint.Basic remote = session.getBasicRemote();
                final String json = gson.toJson(msg);
                remote.sendText(json);
                break;
            }
        }
    }


}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Msg {
    String id;
    String msg;
}
